//
//  CommuniqueController.m
//  Communique
//
//  Created by Thomas on 22/08/2008.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "TerminalWindow.h"
#import "CommuniqueController.h"
#import "Bookmark.h"

static NSString *SUPPORT_DIRECTORY = @"~/Library/Application Support/Communique/";

@implementation CommuniqueController

#pragma mark -
#pragma mark Startup and Shutdown

- (id) init
{
	// apparently singleton objects should no be used in NIBs, naughty naughty
	static id          sharedInstance = nil;
		
	if(nil == sharedInstance)
	{
		sharedInstance = [super init];
        _bookmarks = [[NSMutableArray alloc] init];		
		_windows  = [[NSMutableArray alloc] init];
	}
	else
	{
		[self release];
	}
	return [sharedInstance retain];
}

#pragma mark -
#pragma mark Simple Accessors

- (NSMutableArray *) bookmarks
{
    return _bookmarks;
}

- (void) setBookmarks: (NSArray *)newBookmarks
{
    if (_bookmarks != newBookmarks)
    {
        [_bookmarks autorelease];
        _bookmarks = [[NSMutableArray alloc] initWithArray: newBookmarks];
    }
}

- (NSString *) pathForDataFile { 
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	NSString *folder = [SUPPORT_DIRECTORY stringByExpandingTildeInPath]; 
	if ([fileManager fileExistsAtPath: folder] == NO) { 
		[fileManager createDirectoryAtPath: folder attributes: nil]; 
	} 
	NSString *fileName = @"Communique.sshdata"; 
	return [folder stringByAppendingPathComponent: fileName]; 
} 

- (void) saveDataToDisk { 
	NSString * path = [self pathForDataFile]; 
	NSMutableDictionary * rootObject = [NSMutableDictionary dictionary]; 
	[rootObject setValue: [self bookmarks] forKey:@"bookmarks"]; 
	[NSKeyedArchiver archiveRootObject: rootObject toFile: path];
} 

- (void) loadDataFromDisk { 
	NSString * path = [self pathForDataFile]; 
	NSDictionary * rootObject;
	rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; 
	[self setBookmarks: [rootObject valueForKey:@"bookmarks"]];
} 

// NSApplication delegate methods
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
    putenv("TERM_PROGRAM=Communique.app");
}

- (void) awakeFromNib { 
	[NSApp setDelegate: self]; 
	[self loadDataFromDisk];
	[self updateMenus];
	[self createStatusItem];
	
	[self newWindow:self];
	
	// add KVO to listen for changes to the bookmarks
	//[self addObserver:self forKeyPath:@"bookmarks" options:(NSKeyValueObservingOptionNew) context:NULL];
	//NSRange r;
	//r.location = 0;
	//r.length = [_bookmarks count];
	//NSIndexSet *ix = [[NSIndexSet alloc] initWithIndexesInRange:r];
	//[_bookmarks addObserver:self toObjectsAtIndexes:ix forKeyPath:@"name" options:(NSKeyValueObservingOptionNew) context:NULL];
	//
	//[_bookmarks addObserver:<#(NSObject *)observer#> toObjectsAtIndexes:<#(NSIndexSet *)indexes#> forKeyPath:<#(NSString *)keyPath#> options:<#(NSKeyValueObservingOptions)options#> context:<#(void *)context#>:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew) context:NULL];
	
	//NSLog (@"%@", [_bookmarks valueForKeyPath:@"name"]);
} 

- (void)observeValueForKeyPath:(NSString *)keyPath
			ofObject:(id)object
			change:(NSDictionary *)change
			context:(void *)context
{
	// bookmarks changed ... update
    if ([keyPath isEqual:@"name"]) {
		[self updateMenus];
	}

    // be sure to call the super implementation
    // if the superclass implements it
    [super observeValueForKeyPath:keyPath
                ofObject:object
				change:change
				context:context];
}

- (void) applicationWillTerminate: (NSNotification *)note {
	[self saveDataToDisk];
} 

- (void) createStatusItem {
    _statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
    
    NSBundle *bundle = [NSBundle mainBundle];
    _statusImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"statusicon" ofType:@"png"]];
    [_statusItem setImage:_statusImage];
    [_statusItem setMenu:_dockMenu];
    [_statusItem setToolTip:@"Communiqué"];
    [_statusItem setHighlightMode:YES];
}

- (void) updateMenus {
	// dock menu
	if (_dockMenu==nil)
		_dockMenu = [[NSMenu alloc] init];
	
	NSApplication* app = [NSApplication sharedApplication];
	NSMenuItem* numitmBookmarks  = [[app mainMenu] itemWithTitle:@"Bookmarks"];		
	NSMenu* mnuBookmarks = [numitmBookmarks submenu];	
	
	[mnuBookmarks setMenuChangedMessagesEnabled:NO];
	
	[_dockMenu addItemWithTitle:@"Organize Bookmarks..." action:@selector(dockMenuManageBookmarks:) keyEquivalent:@""];
	[_dockMenu addItem:[NSMenuItem separatorItem]];
	
	NSEnumerator *e = [_bookmarks objectEnumerator ];
	Bookmark *b;
	int counter = 0;
	while (b = [ e nextObject ]) {
		NSMenuItem *menuItem = [_dockMenu addItemWithTitle:b.name action:@selector(dockMenuBookmark:) keyEquivalent:@""];
		[menuItem setTag:counter];
		
		NSMenuItem *menuItem1 = [mnuBookmarks addItemWithTitle:b.name action:@selector(dockMenuBookmark:) keyEquivalent:@""];
		[menuItem1 setTag:counter];
		
		counter++;
	}	
	
	[mnuBookmarks setMenuChangedMessagesEnabled:YES];
	[mnuBookmarks update];	
}

// Action methods
- (IBAction) launchSSH:(id)sender
{
	int row = [bookmarksTable selectedRow];
	Bookmark* bookmark = [_bookmarks objectAtIndex: row];
	[_currentTerminalWindow createTab:bookmark];
}

- (IBAction)newWindow:(id)sender
{
    _currentTerminalWindow = [[TerminalWindow alloc] initWithWindowNibName:@"TerminalWindow"];
	
	//[_currentTerminalWindow setDelegate:self];
	[_currentTerminalWindow showWindow:self];
	
	[_windows addObject:_currentTerminalWindow];
}

- (IBAction)dockMenuManageBookmarks:(id)sender
{
	[_bookmarksWindow makeKeyAndOrderFront:sender];
}

- (IBAction)dockMenuBookmark:(id)sender
{
	Bookmark* bookmark = [_bookmarks objectAtIndex: [sender tag]];
	[_currentTerminalWindow createTab:bookmark];
}


// Dock menu
- (NSMenu *)applicationDockMenu:(NSApplication *)sender
{
	//[self updateMenu];
    return _dockMenu;
}
@end
